package com.aixingfu.sports.ui.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aixingfu.sports.Adapter.GridImageAdapter;
import com.aixingfu.sports.MVP.contract.UserCheckContract;
import com.aixingfu.sports.MVP.contract.UserUploadContract;
import com.aixingfu.sports.MVP.presenter.UserCheckPresenter;
import com.aixingfu.sports.MVP.presenter.UserUploadPresenter;
import com.aixingfu.sports.Model.UserCheckModel;
import com.aixingfu.sports.Model.UserUploadModel;
import com.aixingfu.sports.R;
import com.aixingfu.sports.view.BottomDialog;
import com.aixingfu.sports.view.FullyGridLayoutManager;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.orie.librarybase.base.BaseActivity;
import com.orie.librarybase.utils.MoneyEditUtils;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogChooseImage;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.vondear.rxui.view.dialog.RxDialogChooseImage.LayoutType.TITLE;

//身份验证
@Route(path = "/main/IdentityVerificationActivity")
public class IdentityVerificationActivity extends BaseActivity implements BottomDialog.OnBottomMenuItemClickListener, UserUploadContract.MyView, UserCheckContract.MyView {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_add_img)
    ImageView ivAddImg;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.iv_positive)
    ImageView ivPositive;
    @BindView(R.id.rl_positive)
    RelativeLayout rlPositive;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.rl_members)
    RelativeLayout rlMembers;
    @BindView(R.id.rl_add_more)
    RelativeLayout rlAddMore;
    @BindView(R.id.iv_member)
    ImageView ivMember;
    @BindView(R.id.recycle_other)
    RecyclerView recycleOther;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.iv_add1)
    ImageView ivAdd1;
    @BindView(R.id.iv_add2)
    ImageView ivAdd2;
    @BindView(R.id.iv_add3)
    ImageView ivAdd3;

    private Uri resultUri;

    private GridImageAdapter gridImageAdapter;
    private Intent intent;
    private final int PICK = 3;
    private static final int REQUEST_TAKE_PHOTO = 0;// 拍照
    private static final int REQUEST_CROP = 1;// 裁剪
    private static final int SCAN_OPEN_PHONE = 2;// 相册
    private static final int REQUEST_PERMISSION = 100;
    private Uri imgUri; // 拍照时返回的uri
    private Uri mCutUri;// 图片裁剪时返回的uri
    private File imgFile;// 拍照保存的图片文件
    private boolean hasPermission = false;
    private BottomDialog bottomDialog;
    private UserUploadPresenter userUploadPresenter;

    private UserCheckPresenter userCheckPresenter;
    private int POSITION = 1;
    private String positiveUri="",backUri="",memberUri="",otherUri= "";
    private String[] uriStr = {};
    private String path;
    private List<String> imgList = new ArrayList();
    private String jsonString;
    private String type = "";
    private String member_id = "";

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_identity_verification;
    }

    public static void startActivityByRoute() {
        ARouter.getInstance().build("/main/IdentityVerificationActivity").navigation();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();
        type = bundle.getString("type", "");
        member_id = bundle.getString("member_id", "");
        bottomDialog = new BottomDialog(this, R.layout.dialog_bottom_layout, new int[]{R.id.pick_photo_album, R.id.pick_photo_camera, R.id.pick_photo_cancel});
        bottomDialog.setOnBottomMenuItemClickListener(this);
        initWidget();
        userUploadPresenter = new UserUploadPresenter();
        userUploadPresenter.attachView(this);
        userCheckPresenter = new UserCheckPresenter();
        userCheckPresenter.attachView(this);

    }

    @Override
    protected void initEvent() {
    }

    @Override
    protected void beforeInit() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查是否有存储和拍照权限
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    && checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                    ) {
                hasPermission = true;
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, REQUEST_PERMISSION);
            }
        } else {
            hasPermission = true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                hasPermission = true;
            } else {
                Toast.makeText(this, "权限授予失败！", Toast.LENGTH_SHORT).show();
                hasPermission = false;
            }
        }
    }

    @OnClick({R.id.rl_positive, R.id.rl_back, R.id.rl_members, R.id.rl_add_more, R.id.tv_back, R.id.tv_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_positive:

                POSITION = 1;
                bottomDialog.show();
                break;
            case R.id.rl_back:
                POSITION = 2;
                bottomDialog.show();
                break;
            case R.id.rl_members:
                POSITION = 3;
                checkPermissions();
                Toast.makeText(IdentityVerificationActivity.this, "拍照", Toast.LENGTH_SHORT).show();
                if (hasPermission) {
                    takePhone();
                }
//                bottomDialog.show();
//                intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                startActivityForResult(intent, PICK);
                break;
            case R.id.rl_add_more:
                break;
            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_next:
                if (TextUtils.isEmpty(memberUri)){
                    RxToast.normal(IdentityVerificationActivity.this,"请上传照片").show();
                }else {
                    getUserCheck();
                }

                break;
        }
    }
    public void getUserCheck(){
        if (userCheckPresenter.isViewAttached()){
            HashMap<String,String> map = new HashMap<>();
            map.put("paper_face",positiveUri);
            map.put("paper_opposite", backUri);
            map.put("user_photo",memberUri);
            if (TextUtils.isEmpty(jsonString)){
                map.put("other_photo","");
            }else {
                map.put("other_photo", jsonString);
            }
            userCheckPresenter.getUserCheck(map);
        }
    }
    private void initDialogChooseImage() {
        RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(IdentityVerificationActivity.this, TITLE);
        dialogChooseImage.show();
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            //第一种方式，弹出选择和拍照的dialog
            showPop(SUMBER);
        }
    };
    private List<LocalMedia> selectList = new ArrayList<>();
    private int maxSelectNumber = 9;
    private int sumber;
    private int SUMBER = 1;
    private PopupWindow pop;
    private int maxSelectNum = 9;
    List<LocalMedia> images;

    private void initWidget() {
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(ChannelContractActivity.this, LinearLayoutManager.HORIZONTAL, false));
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        int spanCount = 3; // 3 columns
        int spacing = 30; // 50px
        boolean includeEdge = false;
        recycleOther.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
        recycleOther.setLayoutManager(manager);

        gridImageAdapter = new GridImageAdapter(this, onAddPicClickListener);
        gridImageAdapter.setList(selectList);
        gridImageAdapter.setSelectMax(maxSelectNumber);
        recycleOther.setAdapter(gridImageAdapter);
//        gridImageAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(int position, View v) {
//                if (selectList.size() > 0) {
//                    LocalMedia media = selectList.get(position);
//                    String pictureType = media.getPictureType();
//                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
//                    switch (mediaType) {
//                        case 1:
//                            // 预览图片 可自定长按保存路径
//                            //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
//                            PictureSelector.create(ChannelTraderQualificationsActivity.this).externalPicturePreview(position, selectList);
//                            break;
//                        case 2:
//                            // 预览视频
//                            PictureSelector.create(ChannelTraderQualificationsActivity.this).externalPictureVideo(media.getPath());
//                            break;
//                        case 3:
//                            // 预览音频
//                            PictureSelector.create(ChannelTraderQualificationsActivity.this).externalPictureAudio(media.getPath());
//                            break;
//                    }
//                }
//            }
//        });
        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(IdentityVerificationActivity.this);
                } else {
                    Toast.makeText(IdentityVerificationActivity.this,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }
    private void showPop(final int sumber) {
        this.sumber = sumber;
        View bottomView = View.inflate(IdentityVerificationActivity.this, R.layout.layout_bottom_dialog, null);
        TextView mAlbum = (TextView) bottomView.findViewById(R.id.tv_album);
        TextView mCamera = (TextView) bottomView.findViewById(R.id.tv_camera);
        TextView mCancel = (TextView) bottomView.findViewById(R.id.tv_cancel);

        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        pop.setAnimationStyle(R.style.main_menu_photo_anim);
        pop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                POSITION = 4;
                int i = view.getId();
                if (i == R.id.tv_album) {//相册
                    if (sumber == SUMBER) {
                        PictureSelector.create(IdentityVerificationActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .compress(true)
                                .maxSelectNum(maxSelectNum)
                                .minSelectNum(1)
                                .imageSpanCount(4)
                                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                                .enableCrop(true)// 是否裁剪 true or false
                                .compress(true)// 是否压缩 true or false
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    } else {
                        PictureSelector.create(IdentityVerificationActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .compress(true)
                                .maxSelectNum(maxSelectNum)
                                .minSelectNum(1)
                                .imageSpanCount(4)
                                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                                .enableCrop(true)// 是否裁剪 true or false
                                .compress(true)// 是否压缩 true or false
//                                .compressSavePath(getCompressPath())//压缩图片自定义保存地址
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    }
// 进入相册 以下是例子：用不到的 api 可以不写
                } else if (i == R.id.tv_camera) {//拍照
                    PictureSelector.create(IdentityVerificationActivity.this)
                            .openCamera(PictureMimeType.ofImage())
                            .compress(true)
//                            .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                            .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                            .enableCrop(true)// 是否裁剪 true or false
                            .compress(true)// 是否压缩 true or false
                            .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                            .forResult(PictureConfig.CHOOSE_REQUEST);

                } else if (i == R.id.tv_cancel) {//取消
                    //closePopupWindow();

                }
                closePopupWindow();
            }
        };

        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
        mCancel.setOnClickListener(clickListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    images = PictureSelector.obtainMultipleResult(data);

                                    for (int i = 0; i < images.size(); i++) {
                                        path = images.get(i).getPath();
                                        File mfile = new File(path);
                                        userUploadPresenter.getUserUpload(mfile);
                                    }
                    selectList.addAll(images);
//                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    gridImageAdapter.setList(selectList);
                    gridImageAdapter.notifyDataSetChanged();
//
                    break;

                // 拍照并进行裁剪
                case REQUEST_TAKE_PHOTO:
//                    Log.e(TAG, "onActivityResult: imgUri:REQUEST_TAKE_PHOTO:" + imgUri.toString());
                    cropPhoto(imgUri, true);
                    break;
                // 裁剪后设置图片
                case REQUEST_CROP:
                            try {
                                String realPathFromURI = getRealFilePath(IdentityVerificationActivity.this, mCutUri);
                                File mfile = new File(realPathFromURI);
                                userUploadPresenter.getUserUpload(mfile);
                            } catch (Exception e) {
                                e.printStackTrace();
                        }
//                    Log.e(TAG, "onActivityResult: imgUri:REQUEST_CROP:" + mCutUri.toString());
                    break;
                // 打开图库获取图片并进行裁剪
                case SCAN_OPEN_PHONE:
//                    Log.e(TAG, "onActivityResult: SCAN_OPEN_PHONE:" + data.getData().toString());
                    cropPhoto(data.getData(), false);
                    break;
                // 表示 调用照相机拍照
                case PICK:
                    if (resultCode == RESULT_OK) {
                        Bundle bundle = data.getExtras();
                        Bitmap bitmap = (Bitmap) bundle.get("data");
//                        imgString = bitmapToBase64(bitmap);
//                        uploadImg();
                    }
                    break;
            }
        }
    }

    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }

    @Override
    public void onBottomMenuItemClick(BottomDialog dialog, View view) {
        switch (view.getId()) {
            case R.id.pick_photo_album:
                checkPermissions();
                Toast.makeText(IdentityVerificationActivity.this, "从相册选取", Toast.LENGTH_SHORT).show();
                if (hasPermission) {
                    openGallery();
                }
                break;
            case R.id.pick_photo_camera:
                checkPermissions();
                Toast.makeText(IdentityVerificationActivity.this, "拍照", Toast.LENGTH_SHORT).show();
                if (hasPermission) {
                    takePhone();
                }
                break;
        }
    }

    // 拍照
    private void takePhone() {
        // 要保存的文件名
        String time = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
        String fileName = "photo_" + time;
        // 创建一个文件夹
        String path = Environment.getExternalStorageDirectory() + "/take_photo";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 要保存的图片文件
        imgFile = new File(file, fileName + ".jpeg");
        // 将file转换成uri
        // 注意7.0及以上与之前获取的uri不一样了，返回的是provider路径
        imgUri = getUriForFile(this, imgFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 添加Uri读取权限
        intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        // 或者
        grantUriPermission("com.aixingfu.sports", imgUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        // 添加图片保存位置
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
        startActivityForResult(intent, REQUEST_TAKE_PHOTO);
    }

    // 从file中获取uri
    // 7.0及以上使用的uri是contentProvider content://com.rain.takephotodemo.FileProvider/images/photo_20180824173621.jpg
    // 6.0使用的uri为file:///storage/emulated/0/take_photo/photo_20180824171132.jpg
    private static Uri getUriForFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context.getApplicationContext(), "com.aixingfu.sports.fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, SCAN_OPEN_PHONE);
    }

    // 图片裁剪
    private void cropPhoto(Uri uri, boolean fromCapture) {
        Intent intent = new Intent("com.android.camera.action.CROP"); //打开系统自带的裁剪图片的intent

        // 注意一定要添加该项权限，否则会提示无法裁剪
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        intent.setDataAndType(uri, "image/*");
        intent.putExtra("scale", true);
        if (Build.MANUFACTURER.equals("HUAWEI")) {
            intent.putExtra("aspectX", 9998);
            intent.putExtra("aspectY", 9999);
        } else {
            // 设置裁剪区域的宽高比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
        }
        // 设置裁剪区域的宽度和高度
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);

        // 取消人脸识别
        intent.putExtra("noFaceDetection", true);
        // 图片输出格式
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        // 若为false则表示不返回数据
        intent.putExtra("return-data", false);

        // 指定裁剪完成以后的图片所保存的位置,pic info显示有延时
        if (fromCapture) {
            // 如果是使用拍照，那么原先的uri和最终目标的uri一致,注意这里的uri必须是Uri.fromFile生成的
            mCutUri = Uri.fromFile(imgFile);
        } else { // 从相册中选择，那么裁剪的图片保存在take_photo中
            String time = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
            String fileName = "photo_" + time;
            File mCutFile = new File(Environment.getExternalStorageDirectory() + "/take_photo", fileName + ".jpeg");
            if (!mCutFile.getParentFile().exists()) {
                mCutFile.getParentFile().mkdirs();
            }
            mCutUri = Uri.fromFile(mCutFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mCutUri);
        Toast.makeText(this, "剪裁图片", Toast.LENGTH_SHORT).show();
        // 以广播方式刷新系统相册，以便能够在相册中找到刚刚所拍摄和裁剪的照片
        Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intentBc.setData(uri);
        this.sendBroadcast(intentBc);
        startActivityForResult(intent, REQUEST_CROP); //设置裁剪参数显示图片至ImageVie
    }

    @Override
    public void showToast(String msg, String state) {
    }

    @Override
    public void setUserCheck(UserCheckModel data) {
        if (data.getCode() == 1){
            ARouter.getInstance().build("/main/PurchaseCardInformationActivity").withString("type",type).withString("member_id",member_id).navigation();
            RxToast.normal(IdentityVerificationActivity.this,data.getMessage()).show();

        }else {
            RxToast.normal(IdentityVerificationActivity.this,data.getMessage()).show();
        }
    }

    @Override
    public void setUserUpload(UserUploadModel data) {
        if (data.getCode() == 1) {
            if (POSITION == 1){
                ivAdd1.setVisibility(View.GONE);
                positiveUri = data.getData();
                Glide.with(IdentityVerificationActivity.this).load(positiveUri).into(ivPositive);
            }else if (POSITION == 2){
                ivAdd2.setVisibility(View.GONE);
                backUri = data.getData();
                Glide.with(IdentityVerificationActivity.this).load(backUri).into(ivBack);
            }else if (POSITION == 3){
                ivAdd3.setVisibility(View.GONE);
                memberUri = data.getData();
                Glide.with(IdentityVerificationActivity.this).load(memberUri).into(ivMember);
            }else if (POSITION == 4){
                otherUri = data.getData();
                imgList.add(otherUri);
                jsonString = JSON.toJSONString(imgList);
            }
            RxToast.normal(IdentityVerificationActivity.this, data.getMessage()).show();
        }else {
            RxToast.normal(IdentityVerificationActivity.this, data.getMessage()).show();
        }
    }

    @Override
    public void showLoading() {
showLoadingDialog();
    }

    @Override
    public void hideLoading() {
dismissLoadingDialog();
    }

    @Override
    public Context getMyContext() {
        return this;
    }

    /**
     * uri转path
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) {
            return null;
        }
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
    //关闭软键盘
    public void hideIputKeyboard() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                InputMethodManager mInputKeyBoard = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    mInputKeyBoard.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                }
            }
        });
    }
}
